// request.js：统一封装fetch请求、拼接baseURL、加token、统一处理
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { API_BASE_URL } from '@/config/api'

const baseURL = API_BASE_URL
// const timeout = 5000

async function request(url, options = {}) {
  // 添加token
  if (store.getters.token) {
    options.headers = options.headers || {}
    options.headers['token'] = getToken()
  }

  // // 设置超时
  // const controller = new AbortController()
  // const timeoutId = setTimeout(() => controller.abort(), timeout)
  // options.signal = controller.signal

  try {
    console.log('Request URL:', `${baseURL}${url}`)
    console.log('Request options:', options)
    const response = await fetch(`${baseURL}${url}`, options)
    console.log('Response status:', response.status)
    // clearTimeout(timeoutId)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()

    // 处理业务错误
    if (data.code !== 1) {
      Message({
        message: data.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 处理token相关错误
      if (data.code === 50008 || data.code === 50012 || data.code === 50014) {
        await MessageBox.confirm('登录已过期，请重新登录', '确认登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await store.dispatch('user/resetToken')
        location.reload()
      }
      throw new Error(data.msg || 'Error')
    }

    return data
  } catch (error) {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    throw error
  }
}

export default {
  get(url, options = {}) {
    // 处理GET请求的params参数
    if (options.params) {
      const params = new URLSearchParams()
      Object.keys(options.params).forEach(key => {
        if (options.params[key] !== undefined && options.params[key] !== null) {
          params.append(key, options.params[key])
        }
      })
      url += (url.includes('?') ? '&' : '?') + params.toString()
    }
    return request(url, {
      ...options,
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        ...options?.headers
      }
    })
  },
  post(url, data, options) {
    const isFormData = data instanceof FormData
    // 处理POST请求的params参数
    if (options && options.params) {
      const params = new URLSearchParams()
      Object.keys(options.params).forEach(key => {
        if (options.params[key] !== undefined && options.params[key] !== null) {
          params.append(key, options.params[key])
        }
      })
      url += (url.includes('?') ? '&' : '?') + params.toString()
    }
    return request(url, {
      ...options,
      method: 'POST',
      headers: {
        ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
        ...options?.headers
      },
      body: isFormData ? data : JSON.stringify(data)
    })
  },
  put(url, data, options) {
    const isFormData = data instanceof FormData
    return request(url, {
      ...options,
      method: 'PUT',
      headers: {
        ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
        ...options?.headers
      },
      body: isFormData ? data : JSON.stringify(data)
    })
  },
  delete(url, data, options) {
    const isFormData = data instanceof FormData
    return request(url, {
      ...options,
      method: 'DELETE',
      headers: {
        ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
        ...options?.headers
      },
      body: data ? (isFormData ? data : JSON.stringify(data)) : undefined
    })
  }
}
